import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Tag, Typography, message, Modal, Spin } from 'antd';
import { DownloadOutlined, ReloadOutlined, CheckCircleOutlined, CloseCircleOutlined, SyncOutlined, FileExcelOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { menuAPI } from '../utils/api';

const { Title, Text } = Typography;

const ImportCenterPage = () => {
  const [loading, setLoading] = useState(false);
  const [jobs, setJobs] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const fetchJobs = async (page = 1, pageSize = 10) => {
    try {
      setLoading(true);
      // 这里应该调用获取导入任务列表的API
      // 由于API尚未实现，这里使用模拟数据
      const mockJobs = [
        {
          job_id: 'ad83533b-afcc-441e-8807-91032bb65c1a',
          status: 'failed',
          import_type: 'menu',
          total_rows: 0,
          valid_rows: 0,
          error_rows: 30,
          created_at: '2025-09-04T07:33:35.000Z',
          updated_at: '2025-09-04T07:33:35.000Z',
          admin_id: 1,
          file_name: 'menu_template.xlsx'
        },
        {
          job_id: 'f06300b0-cb26-4f55-83e3-7f6c7a2eff49',
          status: 'validated',
          import_type: 'menu',
          total_rows: 5,
          valid_rows: 5,
          error_rows: 0,
          created_at: '2025-09-04T07:27:47.000Z',
          updated_at: '2025-09-04T07:27:47.000Z',
          admin_id: 1,
          file_name: 'menu_data.xlsx'
        }
      ];

      // 模拟API响应
      setTimeout(() => {
        setJobs(mockJobs);
        setPagination({
          ...pagination,
          current: page,
          total: mockJobs.length
        });
        setLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取导入任务列表失败:', error);
      message.error({ key: 'fetch-jobs-error', content: '获取导入任务列表失败: ' + (error.response?.data?.message || error.message) });
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchJobs();
  }, []);

  const handleTableChange = (pagination) => {
    fetchJobs(pagination.current, pagination.pageSize);
  };

  const handleRefresh = () => {
    fetchJobs(pagination.current, pagination.pageSize);
  };

  const handleDownloadReport = async (jobId, reportType = 'validate') => {
    try {
      message.loading({ content: '正在下载报告...', key: `download-${reportType}-${jobId}`, duration: 0 });
      
      let blobRes;
      if (reportType === 'validate') {
        blobRes = await menuAPI.getValidateReport(jobId);
      } else if (reportType === 'commit') {
        blobRes = await menuAPI.getCommitReport(jobId);
      }
      
      const url = window.URL.createObjectURL(new Blob([blobRes.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${reportType === 'validate' ? '校验' : '导入'}_报告_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy(`download-${reportType}-${jobId}`);
      message.success('报告下载成功');
    } catch (error) {
      console.error('下载报告失败:', error);
      message.destroy(`download-${reportType}-${jobId}`);
      message.error('下载报告失败: ' + (error.response?.data?.message || error.message));
    }
  };

  const handleCommitImport = async (jobId) => {
    try {
      Modal.confirm({
        title: '确认导入',
        content: '确定要提交此导入任务吗？',
        onOk: async () => {
          try {
            message.loading({ content: '正在提交导入...', key: `commit-${jobId}`, duration: 0 });
            const response = await menuAPI.commitImport(jobId);
            
            message.destroy(`commit-${jobId}`);
            if (response.data?.success) {
              message.success('导入成功！');
              // 刷新任务列表
              fetchJobs(pagination.current, pagination.pageSize);
            } else {
              message.error('导入失败: ' + (response.data?.message || '未知错误'));
            }
          } catch (error) {
            console.error('提交导入失败:', error);
            message.destroy(`commit-${jobId}`);
            message.error('提交导入失败: ' + (error.response?.data?.message || error.message));
          }
        }
      });
    } catch (error) {
      console.error('提交导入失败:', error);
      message.error('提交导入失败: ' + (error.response?.data?.message || error.message));
    }
  };

  const getStatusTag = (status) => {
    const statusConfig = {
      uploaded: { color: 'blue', text: '已上传', icon: <FileExcelOutlined /> },
      validating: { color: 'processing', text: '校验中', icon: <SyncOutlined spin /> },
      validated: { color: 'success', text: '校验通过', icon: <CheckCircleOutlined /> },
      failed: { color: 'error', text: '校验失败', icon: <CloseCircleOutlined /> },
      committing: { color: 'processing', text: '导入中', icon: <SyncOutlined spin /> },
      completed: { color: 'success', text: '导入完成', icon: <CheckCircleOutlined /> }
    };
    
    const config = statusConfig[status] || { color: 'default', text: status, icon: null };
    
    return (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    );
  };

  const columns = [
    {
      title: '任务ID',
      dataIndex: 'job_id',
      key: 'job_id',
      width: 300,
      render: (text) => <Text copyable>{text}</Text>
    },
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => getStatusTag(status)
    },
    {
      title: '总行数',
      dataIndex: 'total_rows',
      key: 'total_rows'
    },
    {
      title: '有效行数',
      dataIndex: 'valid_rows',
      key: 'valid_rows'
    },
    {
      title: '错误行数',
      dataIndex: 'error_rows',
      key: 'error_rows',
      render: (text) => text > 0 ? <Text type="danger">{text}</Text> : text
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          {record.error_rows > 0 && (
            <Button 
              type="link" 
              size="small"
              icon={<DownloadOutlined />}
              onClick={() => handleDownloadReport(record.job_id, 'validate')}
            >
              错误报告
            </Button>
          )}
          {record.status === 'validated' && (
            <Button 
              type="primary" 
              size="small"
              onClick={() => handleCommitImport(record.job_id)}
            >
              提交导入
            </Button>
          )}
          {record.status === 'completed' && (
            <Button 
              type="link" 
              size="small"
              icon={<DownloadOutlined />}
              onClick={() => handleDownloadReport(record.job_id, 'commit')}
            >
              导入报告
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ 
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '16px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{ 
            background: 'rgba(255,255,255,0.2)',
            borderRadius: '12px',
            padding: '12px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <FileExcelOutlined style={{ fontSize: '32px', color: '#fff' }} />
          </div>
          <div>
            <Title level={2} style={{ margin: 0, color: '#fff' }}>
              导入中心
            </Title>
            <p style={{ margin: '8px 0 0 0', color: 'rgba(255,255,255,0.8)', fontSize: '16px' }}>
              管理所有导入任务，查看状态和报告
            </p>
          </div>
        </div>
      </div>

      <Card 
        title={<Title level={4} style={{ margin: 0, color: '#1a1a1a' }}>导入任务列表</Title>}
        style={{
          borderRadius: '16px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
          border: 'none',
          overflow: 'hidden'
        }}
        extra={
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            style={{ borderRadius: '8px' }}
          >
            刷新
          </Button>
        }
      >
        <Table 
          columns={columns} 
          dataSource={jobs} 
          rowKey="job_id"
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  );
};

export default ImportCenterPage;